// 专门用来处理数据

import TodoDom from "./TodoDom";
import { getTodoList, addTodo, removeTodo, toggleTodo } from "./TodoService";
import { ITodoData } from "./typings";

class TodoEvent extends TodoDom {
  // 操作数据前要接收数据

  private todoData: ITodoData[];

  constructor(todoData: ITodoData[], todoWrapper: HTMLElement) {
    // 继承TodoDom并把初始的容器数据传过去
    super(todoWrapper)
    this.todoData = todoData;
    // 初始化数据
    this.init(this.todoData)
  }

  // private init () { this.initList(this.todoData) }
  @getTodoList // 装饰器
  private init (todoData: ITodoData[]) {
    this.todoData = todoData
    this.initList(this.todoData)
  }

  @addTodo
  public addTodo (todo: ITodoData): undefined | number {
    // 先判断数据去重，有的话就不添加
    const _todo: null | ITodoData = this.todoData.find((item: ITodoData) => item.content === todo.content);

    // addTodo接收一个返回值 如果是undefined就说明已经成功添加、如果返回 1001 数字 就表示重复了添加不了
    if (!_todo) {
      this.todoData.push(todo); // 数据更新
      this.addItem(todo) // 视图更新
      return;
    }

    return 1001;
  }

  @removeTodo
  public removeTodo (target: HTMLElement, id: number): void {
    this.todoData = this.todoData.filter((item: ITodoData) => item.id !== id);
    this.removeItem(target)
  }

  @toggleTodo
  public toggleComplete (target: HTMLElement, id: number): void {
    this.todoData = this.todoData.map((item: ITodoData) => {
      if(item.id === id) {
        item.completed = !item.completed;
        this.changeCompleted(target, item.completed)
      }
      return item;
    })
  }
}

export default TodoEvent;